package com.boding.power.utils;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.jfinal.kit.PropKit;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

public class QiNiuUtil {
	static Logger logger = Logger.getLogger(QiNiuUtil.class);
	private static String ACCESS_KEY = PropKit.get("QINIU_ACCESS_KEY");
	private static String SECRET_KEY = PropKit.get("QINIU_SECRET_KEY");
	private static String bucketname = PropKit.get("QINIU_bucketname");
	
	public static String getToken() {
		// 密钥配置
		Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		String authToken = auth.uploadToken(bucketname);
		return authToken;
	}

	/**
	 * key 返回图片名
	 * 
	 * @param file
	 * @return
	 */
	public static String uploadFile(File file) {
		UploadManager uploadManager = new UploadManager();
		Subject subject = SecurityUtils.getSubject(); // 获取用户名
		String names[] = file.getName().split("\\.");
		if (names.length == 2) {
			String key = UUID.randomUUID().toString() + "." + names[1];
			try {
				uploadManager.put(file, key, getToken());
			} catch (QiniuException e) {
				e.printStackTrace();
			}
			return key;
		}
		return null;
	}

	public static void delFile(String key) {
		Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		// 实例化一个BucketManager对象
		BucketManager bucketManager = new BucketManager(auth);
		try {
			bucketManager.delete(bucketname, key);
		} catch (QiniuException e) {
			logger.info("删除文件失败 " + key);
		}
	}
}
